<template>
  <div>
    <!-- 操作按钮 -->
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
      "
    >
      <div>
        <a-button type="primary" @click="showModal" style="margin-right: 10px">
          新增
        </a-button>
        <a-button type="primary" danger @click="deleteSelect">删除</a-button>
      </div>
      <div style="display: flex; align-items: center">
        <!-- 多个搜索框与按钮在同一行显示 -->
        <a-input
          v-model:value="query.articleTitle"
          placeholder="标题"
          style="width: 100px; margin-right: 10px"
        />
        <a-select
          v-model:value="query.type"
          style="width: 100px; margin-right: 10px"
          placeholder="转载/原创"
        >
          <a-select-option value="0">原创</a-select-option>
          <a-select-option value="1">转载</a-select-option>
        </a-select>
        <!-- 查询按钮 -->
        <a-button
          type="primary"
          @click="handleTableChange"
          style="margin-right: 10px"
        >
          查询
        </a-button>
        <a-button type="primary" @click="clearSearch">清空</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :row-key="(record) => record.id"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <!-- 使用插槽来渲染操作列 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <span>
            <a @click="update(record.id)">编辑</a>
            <a-divider type="vertical" />
            <a @click="recycle(record.id)">回收</a>
            <a-divider type="vertical" />
            <a @click="_delete(record.id)">删除</a>
          </span>
        </template>
        <!-- 渲染头像 -->
        <template v-if="column.key === 'articleCover'">
          <span>
            <a-image :width="40" :src="record.articleCover" />
          </span>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script>
  import { getList, _delete, recycle } from '@/api/article'
  import { Modal } from 'ant-design-vue'
  import moment from 'moment'

  // 定义列的字段
  const columns = [
    {
      title: '作者',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      key: 'menuName',
    },
    {
      title: '文章缩略图',
      dataIndex: 'articleCover',
      key: 'articleCover',
    },
    {
      title: '标题',
      dataIndex: 'articleTitle',
      key: 'articleTitle',
      ellipsis: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '文章类型',
      dataIndex: 'type',
      key: 'type',
      customRender: ({ text }) => (text === 0 ? '原创' : '转载'),
    },
    {
      title: '内容类型',
      dataIndex: 'contentType',
      key: 'contentType',
      customRender: ({ text }) =>
        text === 0 ? '文章' : text === 1 ? '视频' : '题目',
    },
    {
      title: '原文链接',
      dataIndex: 'originalUrl',
      key: 'originalUrl',
      ellipsis: true,
    },
    {
      title: '是否置顶',
      dataIndex: 'isTop',
      key: 'isTop',
      customRender: ({ text }) => (text === 1 ? '是' : '否'),
    },
    {
      title: '是否可评论',
      dataIndex: 'isComment',
      key: 'isComment',
      customRender: ({ text }) => (text === 0 ? '是' : '否'),
    },
    {
      title: '状态值',
      dataIndex: 'status',
      key: 'status',
      customRender: ({ text }) => (text === 1 ? '公开' : '私密'),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      customRender: (text) => {
        return moment(text.value).format('YYYY-MM-DD HH:mm:ss')
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      customRender: (text) => {
        if (text.value) {
          return moment(text.value).format('YYYY-MM-DD HH:mm:ss')
        } else {
          return text.value
        }
      },
    },
    {
      title: '操作',
      key: 'action', // 自定义渲染操作列
      fixed: 'right', // 固定右侧
      width: 150,
    },
  ]
  export default {
    data() {
      return {
        data: [], // 列表数据
        pagination: {
          showLessItems: true,
          showQuickJumper: true,
          showSizeChanger: true,
        }, // 分页参数
        query: {}, //查询参数
        loading: false, // 是否加载
        columns, // 表格列
        selectedRowKeys: [], // 选中的列
      }
    },
    computed: {
      hasSelected() {
        return this.selectedRowKeys.length > 0
      },
    },
    mounted() {
      this.fetch()
    },
    methods: {
      // 回收
      recycle(id) {
        Modal.confirm({
          title: 'Confirm',
          content: '确定要回收吗？',
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            recycle({ id: id }).then(() => {
              // 重新查询数据
              this.handleTableChange(this.pagination)
            })
          },
        })
      },
      // 打开新增框
      showModal() {
        this.$router.push('createArticle')
      },
      // 修改数据
      update(id) {
        this.$router.push({ name: 'createArticle', params: { id: id } })
      },
      // 选择
      onSelectChange(selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys)
        this.selectedRowKeys = selectedRowKeys
      },
      // 删除选中
      deleteSelect() {
        this._delete(this.selectedRowKeys)
      },
      // 删除数据
      _delete(id) {
        let ids
        // 此处批量跟单个删除公用，做一下判断
        if (Array.isArray(id)) {
          ids = id
        } else {
          ids = [id]
        }
        if (ids && ids.length > 0) {
          Modal.confirm({
            title: 'Confirm',
            content: '确定要删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              _delete(ids).then(() => {
                // 删除就清空勾选项
                this.selectedRowKeys = []
                // 重新查询数据
                this.handleTableChange(this.pagination)
              })
            },
          })
        }
      },
      // 清空查询参数
      clearSearch() {
        Object.getOwnPropertyNames(this.query).forEach((key) => {
          this.query[key] = null
        })
        this.handleTableChange(this.pagination)
      },
      // 查询数据
      handleTableChange(pagination) {
        const pager = { ...this.pagination }
        pager.current = pagination.current
        this.pagination = pager
        this.fetch()
      },
      // 请求后台
      fetch() {
        this.loading = true
        getList({
          pageSize: this.pagination.pageSize,
          current: this.pagination.current,
          ...this.query,
        }).then(({ data }) => {
          const pagination = { ...this.pagination }
          pagination.total = data.total
          this.loading = false
          this.data = data.records
          console.log(this.data)
          this.pagination = pagination
        })
      },
    },
  }
</script>
<style></style>
